<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-left">
        <el-input size="mini" v-model="searchKey" placeholder="请输入用户名查询" style="width: 200px" class="filter-item"
          @keyup.enter.native="handleFilter" @input="handleFilter" />
        <!-- <el-button
          v-waves
          size="mini"
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >
          查询
        </el-button> -->
      </div>
    </div>
    <el-table :data="pageList" border stripe fit highlight-current-row v-loading="listLoading" style="width: 100%">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="nick" label="用户名" align="center">
      </el-table-column>
      <el-table-column label="用户头像" align="center">
        <template slot-scope="{ row }">
          <img :src="row.avatar_url" alt="" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否管理员" align="center">
        <template slot-scope="{ row }">
          <el-switch :value="row.is_admin" :active-value="1" :inactive-value="0"
            @change="changeStatus(row)"></el-switch>
        </template>
      </el-table-column> -->
      <el-table-column label="角色权限" align="center">
        <template slot-scope="{ row }">
          <el-popover placement="right" trigger="hover">
            <div style="margin-bottom:5px;font-weight:900;">修改用户角色权限</div>
            <el-button size="mini" v-for="item in userRoleLists" :key="item.role_code" round
              @click="handleChangeUserRole(row, item)">{{ item.role_name }}</el-button>
            <el-button type="text" slot="reference">
              <span v-if="row.role_name">{{ row.role_name }}</span>
              <span v-else>普通用户</span>
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="dept_name_list" label="归属部门" align="center">
      </el-table-column>
      <el-table-column prop="user_title" label="用户职位" align="center">
      </el-table-column>
      <el-table-column prop="hours_amount" label="工时金额（元/小时）" align="center">
        <template slot-scope="{ row }">
          <el-popover placement="right" trigger="hover">
            <div style="margin-bottom:5px;font-weight:900;">请选择工时金额</div>
            <el-button size="mini" v-for="item in workHoursAmount" :key="item.code" round
              @click="changeUserWorkAmount(row, item)">{{ item.amount }}</el-button>
            <el-button type="text" slot="reference">
              <span v-if="row.hours_amount">{{ row.hours_amount }}</span>
              <span v-else>请选择金额</span>
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="user_status" label="用户状态" align="center">
        <template slot-scope="{ row }">
          <el-switch :value="row.user_status" :active-value="1" :inactive-value="0"
            @change="changeUserStatus(row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.created_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.updated_at | formate }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getPageList" />
  </div>
</template>

<script>
import {
  getUserList,
  getDataByCode,
  updateUserById,
  getUserDetails,
  updateUserHoursAmount,
  changeUserRole
} from "@/api/user";

import { getUserRoleLists } from "@/api/user-role";
import waves from "@/directive/waves"; // waves directive
import { curentTime } from "@/filters/index";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

export default {
  name: "Order",
  components: { Pagination },
  directives: { waves },
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  data() {
    return {
      // 订单数据
      pageList: [],
      // 订单总数
      total: 0,
      // 加载
      listLoading: true,
      // 查询条件
      listQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      searchKey: "",
      // 当前登录用户信息
      userDetail: {},
      workHoursAmount: [],
      userRoleLists: [], // 角色列表
    };
  },
  async created() {
    // 获取配置数据
    getDataByCode({ code: "WorkHoursAmount" }).then((res) => {
      this.workHoursAmount = res.data.WorkHoursAmount || [];
    });
    await this.getPageList();
    this.getUserDetail();
    this.getUserRoleLists();
  },
  methods: {
    //  修改用户角色信息
    async handleChangeUserRole(row,item){
      console.log("changeUserRole",row,item)
      const res = await changeUserRole({ userId: row.id, roleId: item.id });
      console.log("changeUserRole",res)
      if(res && res.success){
        this.getPageList();
        this.$message.success("修改成功");
      }else{
        this.$message.error("修改失败");
      }
    },
    //  查询所以角色列表
    async getUserRoleLists() {
      const res = await getUserRoleLists({ pageNum: 1, pageSize: 200 });
      this.userRoleLists = res.data.items || [];
    },
    // 按需查询
    async handleFilter() {
      this.listQuery.searchKey = this.searchKey;
      this.listQuery.pageNum = 1;
      await this.getPageList();
    },

    // 查询列表
    async getPageList() {
      try {
        const res = await getUserList(this.listQuery);
        this.total = res.data.total;
        this.pageList = res.data.lists;
        this.listLoading = false;
      } catch (error) {
        console.log(error);
      }
    },

    // 修改用户权限
    changeStatus(row) {
      let data = {
        id: row.id,
        key: "is_admin",
        value: row.is_admin == 0 ? 1 : 0,
      };
      this.$confirm("确认修改该用户权限吗？", "操作确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateUserById(data).then((res) => {
            this.$message.success("修改成功");
            this.getPageList();
          });
        })
        .catch(() => { });
    },

    // 修改用户状态
    changeUserStatus(row) {
      let data = {
        id: row.id,
        key: "user_status",
        value: row.user_status == 0 ? 1 : 0,
      };
      let title = row.user_status == 0 ? "启用" : "禁用";
      this.$confirm(`确认${title}该用户吗？`, "操作确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (row.nick == this.userDetail.nick) {
            this.$router.push({ path: "/401" });
            updateUserById(data);
          } else {
            updateUserById(data).then((res) => {
              this.getPageList();
              this.$message.success(`${title}成功`);
            });
          }
        })
        .catch(() => { });
    },

    // 获取用户详情
    getUserDetail() {
      getUserDetails().then((res) => {
        this.userDetail = res.data;
      });
    },
    //  修改用户工时单价
    async changeUserWorkAmount(row, item) {
      console.log(row, item);
      const res = await updateUserHoursAmount({
        id: row.id,
        hoursAmount: item.amount
      });
      console.log("res:::::::", res)
      this.getPageList();
    },
  },
};
</script>

<style lang="scss" scoped>
.filter-container {
  display: flex;
  justify-content: space-between;
}
</style>